package com.example.urmsadmin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.urmsadmin.Util.PermissionService;
import com.example.urmsadmin.Util.ValidatorUtil;
import com.example.urmsadmin.entity.SysRole;
import com.example.urmsadmin.entity.SysUser;
import com.example.urmsadmin.service.SysRoleMenuService;
import com.example.urmsadmin.service.SysRoleService;
import com.example.urmsadmin.service.SysUserRoleService;
import com.example.urmsadmin.service.impl.SysRoleMenuServiceImpl;
import com.example.urmsadmin.service.impl.SysRoleServiceImpl;
import com.example.urmsadmin.service.impl.SysUserRoleServiceImpl;
import com.example.urmsadmin.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 角色信息表(SysRole)表控制层
 *
 * @author makejava
 * @since 2022-07-12 08:44:11
 */
@RestController
@Slf4j
@RequestMapping(value = "/sysRole")
public class SysRoleController {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private SysRoleMenuService roleMenuService;

    /**
     * @param roleName  用户名
     * @param status    角色状态
     * @param pageNo    查询页数
     * @param pageSize  页面大小
     * @return
     */
    @PreAuthorize("@per.hasPermi('system:role:query')")
    @GetMapping("/getRole")
    public CommonResult<Object> getRole(@RequestParam(required = false) String roleName,
                                        @RequestParam(required = false) String status,
                                        Integer pageNo, Integer pageSize)  {
        log.info("执行了===>SysRoleController中的getRole方法");
        //参数一是当前页，参数二是每页个数
        IPage<SysRole> rolePage = new Page<>(pageNo, pageSize);
        //查询条件(可选)
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if (!Objects.equals(roleName, "") && roleName != null) {
            wrapper.like("role_name", roleName);
        }
        if (!Objects.equals(status, "") && status != null) {
            wrapper.like("status", status);
        }
        rolePage = roleService.page(rolePage, wrapper);
        List<SysRole> roles = rolePage.getRecords();
        // 创建分页结果集
        Map<Object, Object> result = new HashMap<>();
        result.put("roles", roles);
        result.put("total", rolePage.getTotal());
        return new CommonResult<>(200, "success", result);
    }

    /**
     * @param role 角色实体
     * @return
     */
    @PreAuthorize("@per.hasPermi('system:role:add')")
    @PostMapping("/addRole")
    public CommonResult<String> addRole(@RequestBody SysRole role){
        log.info("执行了===>SysRoleController中的addRole方法");
        if(ValidatorUtil.isRoleName(role.getRoleName())
        && ValidatorUtil.isRoleKey(role.getRoleKey())
        && ValidatorUtil.isRemark(role.getRemark())){
        }else{
            return new CommonResult<>(233,"数据不合法");
        }
        role.setStatus(role.getStatus().equals("0")?"0":"1");
        role.setCreateTime(new Date());
        boolean save = roleService.save(role);
        return save ? new CommonResult<>(200, "操作成功") : new CommonResult<>(233, "操作失败");
    }

    /**
     * @param type    操作类型
     * @param roleIds 操作用户的id的字符串,以逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/handleRole/{type}")
    public CommonResult<String> handleRole(@PathVariable("type") Integer type, String roleIds) {
        log.info("执行了===>SysRoleController中的handleRole方法");
        //转换成数组 需要操作的用户的id数组
        String[] ids = roleIds.split(",");
        if (type == 1) {//启用
            if(!permissionService.hasPermi("system:role:statusOn")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysRole role = roleService.getById(Integer.parseInt(id));
                role.setStatus("0");//设置为有效的用户
                roleService.update(role, new UpdateWrapper<SysRole>().eq("role_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 2) {//禁用
            if(!permissionService.hasPermi("system:role:statusOff")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysRole role = roleService.getById(Integer.parseInt(id));
                role.setStatus("1");//设置为无效的用户
                roleService.update(role, new UpdateWrapper<SysRole>().eq("role_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 3) {//删除
            if(!permissionService.hasPermi("system:role:remove")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                roleService.removeById(Long.parseLong(id));
                QueryWrapper wrapper = new QueryWrapper();  //删除关联表数据
                wrapper.eq("role_id",id);
                userRoleService.remove(wrapper);
                roleMenuService.remove(wrapper);

            }
            return new CommonResult<>(200, "操作成功");
        } else {
            return new CommonResult<>(233, "操作有误");
        }
    }

    @PreAuthorize("@per.hasPermi('system:role:edit')")
    @PostMapping("/updateRole")
    public CommonResult<String> updateRole(@RequestBody SysRole role) {
        log.info("执行了===>SysRoleController中的updateRole方法");
        if(ValidatorUtil.isRoleName(role.getRoleName())
                && ValidatorUtil.isRoleKey(role.getRoleKey())
                && ValidatorUtil.isRemark(role.getRemark())){
        }else{
            return new CommonResult<>(233,"数据不合法");
        }
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            wrapper = new QueryWrapper<SysRole>().eq("role_id", role.getRoleId());
        // 查询当前用户信息
        SysRole roleData = roleService.getOne(wrapper);

        if (roleData != null) {
            roleData.setUpdateTime(new Date());
            roleData.setRoleName(role.getRoleName());
            roleData.setRoleKey(role.getRoleKey());
            roleData.setStartTime(role.getStartTime());
            roleData.setEndTime(role.getEndTime());
            roleData.setStatus(role.getStatus().equals("0")?"0":"1");
            roleData.setRemark(role.getRemark());

            boolean update = roleService.update(roleData, wrapper);
            return update ? new CommonResult<>(200, "更新用户信息成功") :
                    new CommonResult<>(233, "更新用户信息失败");
        }else {
            throw new RuntimeException("获取用户信息失败！");
        }
    }

    /**
     * @param roleName 角色名
     * @return
     */
    @GetMapping(value = {"/checkRoleName/{roleName}","/checkRoleName/"})
    public CommonResult<String> checkRoleName(@PathVariable(value = "roleName",required = false) String roleName) {
        log.info("执行了===>SysRoleController中的checkRoleName方法");
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name", roleName);
        SysRole role = roleService.getOne(wrapper);
        if (role == null) {
            return new CommonResult<>(200, "角色名可用");
        } else {
            return new CommonResult<>(233, "角色已存在");
        }
    }
}

